package com.hyk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyk.domain.TradeArea;
import com.hyk.dto.R;
import com.hyk.service.TradeAreaService;
import com.hyk.vo.TradeAreaMarketVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Api(tags = "交易区域控制器")
@RequestMapping("/tradeAreas")
public class TradeAreaController {

    @Resource
    private TradeAreaService tradeAreaService;

    @GetMapping
    @ApiOperation("根据条件查询")
    public R<Page<TradeArea>> list(@ApiIgnore Page<TradeArea> page,
                                   String name, Byte status){
        return R.ok(tradeAreaService.page(page,new LambdaQueryWrapper<TradeArea>().
                like(StringUtils.isNotBlank(name),TradeArea::getName,name).
                eq(status != null,TradeArea::getStatus,status).
                orderByDesc(TradeArea::getCreated)));
    }

    @PostMapping
    @ApiOperation("新增")
    public R add(@RequestBody TradeArea tradeArea){
        boolean save = tradeAreaService.save(tradeArea);
        if (save){
            return R.ok();
        }
        return R.fail();
    }

    @PatchMapping
    @ApiOperation("编辑")
    public R update(@RequestBody TradeArea tradeArea){
        tradeAreaService.updateTradeArea(tradeArea);
        return R.ok();
    }

    @PostMapping("/status")
    @ApiOperation("修改状态")
    public R changeStatus(@RequestBody TradeArea tradeArea){
        boolean update = tradeAreaService.updateById(tradeArea);
        if (update){
            return R.ok();
        }
        return R.fail();
    }

    @GetMapping("/all")
    public R<List<TradeArea>> all(Byte status){
        return R.ok(tradeAreaService.list(new LambdaQueryWrapper<TradeArea>().
                eq(status != null,TradeArea::getStatus,status)));
    }

    @GetMapping("/markets")
    public R<List<TradeAreaMarketVo>> markets(){
        List<TradeAreaMarketVo> list = tradeAreaService.getMarkets(null);
        return R.ok(list);
    }

    @GetMapping("/market/favorite")
    public R<List<TradeAreaMarketVo>> favorite(){
        Long userId = Long.parseLong(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        List<TradeAreaMarketVo> list = tradeAreaService.getMarkets(userId);
        return R.ok(list);
    }
}
